package com.grapevine.contact;

import java.lang.ref.WeakReference;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.AsyncQueryHandler;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemLongClickListener;
import com.grapevine.contact.adapter.ContactAdapter;
import com.grapevine.contact.config.ConfigKey;
import com.grapevine.contact.config.SharePrefareManager;
import com.grapevine.contact.util.AndroidPhoneLocationLoader;
import com.grapevine.contact.util.ContactPhotoLoader;

public class Contact extends ListActivity implements OnItemLongClickListener, OnScrollListener
{

	public static final int NO_SDCARD = 0;
	public static final int SCAN_FILE_ERRLR = 1;
	public static final int SCAN_END = 2;

	private ContactAdapter mAdapter;

	// private Cursor mCursor;

	private ContactPhotoLoader mContactPhotoLoader;
	private AndroidPhoneLocationLoader mAndroidPhoneLocationLoader;

	private String[] proj = { ContactsContract.Contacts._ID, ContactsContract.Contacts.PHOTO_ID,
			ContactsContract.Contacts.DISPLAY_NAME };

	private QueryHandler m_queryHandler;
	private static final int QUERY_TOKEN = 42;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_contact);
		mContactPhotoLoader = new ContactPhotoLoader(this, R.drawable.ic_contact_list_picture);
		mAndroidPhoneLocationLoader = new AndroidPhoneLocationLoader(this);

		// mCursor =
		// getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
		// proj,
		// ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'", null,
		// ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");

		// startManagingCursor(mCursor);
		// mAdapter = new ContactAdapter(this, mCursor, mContactPhotoLoader,
		// mAndroidPhoneLocationLoader);

		getListView().setOnScrollListener(this);
		getListView().setOnItemLongClickListener(this);
		// getListView().setAdapter(mAdapter);

		m_queryHandler = new QueryHandler(this);
//		m_queryHandler.setLoadingJoinSuggestions(true);
//		m_queryHandler.startQuery(QUERY_TOKEN, null, ContactsContract.Contacts.CONTENT_URI, proj,
//				ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'", null, ContactsContract.Contacts.DISPLAY_NAME
//						+ " COLLATE LOCALIZED ASC");
		
	}

	@Override
	protected void onResume()
	{
		mContactPhotoLoader.resume();
		mAndroidPhoneLocationLoader.resume();
		// mCursor.requery();
//		mAdapter.notifyDataSetChanged();
		Editor editor = SharePrefareManager.getEditor(this);
		editor.putInt(ConfigKey.CURRENT_ACTIVITY, 2);
		editor.commit();
		/**
		 * mCursor =
		 * getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
		 * proj, ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'", null,
		 * ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
		 */
		m_queryHandler.cancelOperation(QUERY_TOKEN);
		m_queryHandler.setLoadingJoinSuggestions(true);
		m_queryHandler.startQuery(QUERY_TOKEN, null, ContactsContract.Contacts.CONTENT_URI, proj,
				ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'", null, ContactsContract.Contacts.DISPLAY_NAME
						+ " COLLATE LOCALIZED ASC");
		super.onResume();
	}

	@Override
	protected void onPause()
	{
		super.onPause();
		mContactPhotoLoader.pause();
		mAndroidPhoneLocationLoader.pause();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id)
	{
		super.onListItemClick(l, v, position, id);

		Cursor cursor = (Cursor) mAdapter.getItem(position);

		long nId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID));

		Uri scan = ContentUris.withAppendedId(Contacts.CONTENT_URI, nId);
		Intent intent = new Intent(Intent.ACTION_VIEW, scan);
		startActivity(intent);
	}

	private static final String[] mOperator = { "查看", "编辑", "删除" };

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
	{
		Cursor cursor = (Cursor) mAdapter.getItem(position);
		String title = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

		final long personId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID));

		// final long phoneId =
		// cursor.getLong(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_1, mOperator);

		new AlertDialog.Builder(this).setTitle(title).setAdapter(adapter, new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				Intent intent;
				Uri data = ContentUris.withAppendedId(Contacts.CONTENT_URI, personId);

				switch (which)
				{
				case 0:// 查看
					intent = new Intent(Intent.ACTION_VIEW, data);
					startActivity(intent);
					break;

				case 1:// 编辑
					intent = new Intent(Intent.ACTION_EDIT, data);
					startActivity(intent);
					break;

				case 2: // 删除
					// Uri u =
					// ContentUris.withAppendedId(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
					// phoneId);
					getContentResolver().delete(data, null, null);
					// mCursor.requery();
					mAdapter.notifyDataSetChanged();
					break;

				default:
					break;
				}

			}
		}).create().show();
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		menu.add(0, Menu.FIRST, 0, "添加联系人").setIcon(android.R.drawable.ic_menu_add);
		menu.add(0, Menu.FIRST + 1, 0, "导入/导出").setIcon(R.drawable.ic_menu_import_export);
		return super.onCreateOptionsMenu(menu);
	}

	private static class QueryHandler extends AsyncQueryHandler
	{
		protected final WeakReference<Contact> mActivity;
		protected boolean mLoadingJoinSuggestions = false;

		public QueryHandler(Context context)
		{
			super(context.getContentResolver());
			mActivity = new WeakReference<Contact>((Contact) context);
		}

		public void setLoadingJoinSuggestions(boolean flag)
		{
			mLoadingJoinSuggestions = flag;
		}

		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor)
		{
			final Contact activity = mActivity.get();
			if (activity != null && !activity.isFinishing() && mLoadingJoinSuggestions)
			{
				mLoadingJoinSuggestions = false;
				
				if (null == activity.mAdapter)
				{
					activity.mAdapter = new ContactAdapter(activity, cursor, activity.mContactPhotoLoader,
							activity.mAndroidPhoneLocationLoader);
					activity.getListView().setAdapter(activity.mAdapter);
				}
				else
				{
					activity.mAdapter.changeCursor(cursor);
				}
			}
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{

		boolean ret = true;
		Intent intent;

		switch (item.getItemId())
		{
		case Menu.FIRST:// 添加联系人
			intent = new Intent(Intent.ACTION_INSERT);
			intent.setType("vnd.android.cursor.dir/contact");
			startActivity(intent);
			break;
		case Menu.FIRST + 1: // 导入导出
			importOrOutputContact();
			break;

		default:
			ret = super.onOptionsItemSelected(item);
			break;
		}
		return ret;
	}

	private static final String[] mOperatorVcard = { "从SD卡导入", "导出到SD卡" };

	private void importOrOutputContact()
	{
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_1, mOperatorVcard);

		new AlertDialog.Builder(this).setTitle("导入/导出联系人").setAdapter(adapter, new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				switch (which)
				{
				case 0:// 从SDCARD 卡 导入
					Intent intent = new Intent(Contact.this, ImportVCardActivity.class);
					Contact.this.startActivity(intent);
					break;

				case 1:// 导出到 SDCARD导出
					break;

				default:
					break;
				}
			}
		}).setNegativeButton("取消", null).create().show();
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
	{

	}

	@Override
	protected void onDestroy()
	{
		mContactPhotoLoader.stop();
		mAndroidPhoneLocationLoader.stop();
		// mCursor.close();
		super.onDestroy();
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState)
	{
		if (scrollState == OnScrollListener.SCROLL_STATE_FLING)
		{
			mContactPhotoLoader.pause();
			mAndroidPhoneLocationLoader.pause();
		}
		else
		{
			mContactPhotoLoader.resume();
			mAndroidPhoneLocationLoader.resume();
		}
	}

	public void showToastMessage(String message)
	{

		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

	}
}